#ifndef UPLOADTHREAD_H
#define UPLOADTHREAD_H

#include <QNetworkAccessManager>
#include <PluginsInterface.h>
#include <QNetworkReply>
#include "PostData.h"

struct HostingParams
{
	QString Host;
	QString URI;
	QString URL;
	QString User_Agent;
};

class UploadWorker : public QObject
{
	Q_OBJECT;
public:
	UploadWorker(QObject *parent, QNetworkAccessManager *netMgr);
	bool append(const ImageToUpload &image);
	void run();
	const QList<UploadResult>& allLinks() const;
protected:
	// METHODS
	virtual bool collectPostData() = 0; // Html Form fields, like "dont_resize" or "session_id"
	virtual bool appendImageToPost(const ImageToUpload &image) = 0; // binary fields like "file"
	virtual bool setHeaders(QNetworkRequest &req) = 0;
	virtual QList<UploadResult> parseResponse() const = 0;
	virtual const QUrl hostingUrl() const = 0;
	// DATA
	QNetworkAccessManager *netMgr;
	QNetworkReply *reply;
	PostData data;
	QList<UploadResult> links;
	QList<ImageToUpload> images;
	bool requestFailed;
	bool canceled;
	// ACCESORS
	// EXCEPTIONS
	class MyException{
	public:
		MyException(const QString &errorS) : error(errorS)
		{ }
		QString errorStr() { return error; }
	private:
		const QString error;
	};
	class fileException : public MyException {
	public:
		fileException(const QString &error)
			: MyException(error) { }
	};
protected slots:
	void requestFinished();
	void requestError(QNetworkReply::NetworkError);
	void updateProgress(qint64 value, qint64 max);
public slots:
	void abort();
signals:
	void fileError(int index, QString error);
	void startFile(int index);
	void fileUploaded(int index, UploadResult result);
	void updateStatus(int value, int max, int index);
	void finished();
};


bool reOpenDevice(QIODevice *buffer, QIODevice::OpenMode Mode = QIODevice::ReadOnly );


#endif // UPLOADTHREAD_H
